package apply

import (
	"encoding/base64"
	"fmt"
	"gitee.com/pkg/root"
	"gitee.com/runx/gitctl/pkg/api/conf"
	v1 "gitee.com/runx/gitctl/pkg/api/v1"
	"gitee.com/runx/gitctl/pkg/cli"
	"gitee.com/runx/gitctl/pkg/cli/add"
	"gitee.com/runx/gitctl/pkg/cli/get"
	"gitee.com/runx/gitctl/pkg/cli/ops"
	"gitee.com/runx/gitctl/pkg/cli/update"
	"github.com/spf13/cobra"
	"gopkg.in/yaml.v2"
)

var (
	xFile string
	xConf string
	xCli  *cli.Cli
	dmCmd = &cobra.Command{
		Use:   "apply",
		Short: "apply file info gitea",
		RunE: func(c *cobra.Command, args []string) error {
			res, err := v1.Of(xFile)
			if err != nil {
				fmt.Printf("read file error,reson:%s\n", err)
			}
			ctx := xCli.NewCtx(ops.GetFile, res)
			rsp := &get.Content{}
			if err = ctx.Invoke(rsp); err != nil {
				return err
			}

			if rsp.Sha != "" {
				if rsp.Content == base64.StdEncoding.EncodeToString([]byte(res.Content)) {
					fmt.Printf("file %s no changed\n", rsp.Path)
				} else {
					fmt.Printf("file %s sha is :%s\n", rsp.Path, rsp.Sha)
					res.Sha = rsp.Sha
					ctx = xCli.NewCtx(ops.UpdateFile, res)
					rsp2 := &update.Content{}
					ctx.Invoke(rsp2)
					fmt.Println(rsp2)
				}
			} else {
				res.Sha = rsp.Sha
				ctx = xCli.NewCtx(ops.AddFile, res)
				rsp2 := &add.Content{}
				ctx.Invoke(rsp2)
				fmt.Println(rsp2)
				fmt.Printf("file %s configured\n", rsp.Path)

			}
			return nil
		},
	}
)

func init() {
	homer, _ := conf.Home()
	dmCmd.PersistentFlags().StringVarP(&xFile, "file", "f", "", "apply file into gitee")
	dmCmd.PersistentFlags().StringVarP(&xConf, "config", "c", homer+"/.gitops/config", "tool config file ")
	config := &conf.Config{}
	err := yaml.Unmarshal(conf.GetData(xConf), config)
	if err != nil {

		panic(err)
	}
	xCli = cli.New(config)
	root.AddCmd(dmCmd)
}

func AddCmd(cmds ...*cobra.Command) {
	for i, _ := range cmds {
		dmCmd.AddCommand(cmds[i])
	}
}
